package com.baidu.shoppingmall.auth.visitor;

import com.baidu.shoppingmall.auth.composite.AuthorityNode01;
import com.baidu.shoppingmall.auth.dao.AuthorityDAO;
import com.baidu.shoppingmall.auth.domain.AuthorityPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class CheckRoleAuthorityRelationVisitor01 implements AuthorityVisitor01{

    private Boolean status=false;

    @Autowired
    private AuthorityDAO authorityDAO;

    public Boolean getStatus(){
        return status;
    }

    public CheckRoleAuthorityRelationVisitor01 (){

    }

    @Override
    public void visit(AuthorityNode01 authorityNode01) {
        QueryWrapper<AuthorityPO> queryWrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_id", authorityNode01.getId());
        queryWrapper.allEq(map);
        List<AuthorityPO> authorityPOList = authorityDAO.selectList(queryWrapper);
        List<AuthorityNode01> authorityNode01List = new ArrayList<>(authorityPOList.size());
        authorityPOList.forEach(po->authorityNode01List.add(po.clone(AuthorityNode01.class)));

        if (authorityNode01List!=null&&authorityNode01List.size()>0){
            authorityNode01List.forEach(node->node.accept(this));
        }
        boolean checkResult = checkRolePermissionRelation(authorityNode01.getId());
        if (checkResult){
            this.status=true;
            System.out.println(authorityNode01.getAuthorityComment()+"被使用");
        }else {
            this.status=false;
            System.out.println(authorityNode01.getAuthorityComment()+"未被使用");
        }
    }

    public Boolean checkRolePermissionRelation(Long id){
        Integer usage = authorityDAO.selectById(id).getPermissionUsage();
        if (usage==1){
            return  true;
        }
        return false;
    }
}
